package com.ruc.deke.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruc.deke.dao.DBCourseDAO;
import com.ruc.deke.dao.ModuleDAO;
import com.ruc.deke.dao.UserDAO;
import com.ruc.deke.model.DBRecord;
import com.ruc.deke.service.SqlJudgeService;
import com.ruc.deke.utils.EncryptionDecryption;
import com.ruc.deke.utils.ParseUtil;

/**
 * 获取关于题目的相关信息
 * 
 * @author: cyj
 * @date: 2017年3月30日 下午4:01:43
 */

@Controller
@RequestMapping(value = "/module")
public class ModuleController {

	@Resource(name = "moduleDAOImpl")
	private ModuleDAO moduleDAO;

	@Resource(name = "userDAOImpl")
	private UserDAO userDAO;

	@Resource(name = "sqlJudgeServiceImpl")
	private SqlJudgeService sqlJudgeService;

	@Resource(name = "dbCourseDAOImpl")
	private DBCourseDAO dbCourseDAO;

	@Resource(name = "dataSource_rucsamples")
	private DataSource samplesDataSource;

	@Resource(name = "dataSource_rucdbcourse")
	private DataSource dbDataSource;

	/**
	 * 获取所有的题目分类及所属知识点（侧边栏展示）
	 * 
	 * @return
	 * @author: cyj
	 * @date: 2017年3月30日 下午4:03:41
	 */
	@RequestMapping(value = "/getModules")
	@ResponseBody
	public ArrayList<DBRecord> getModules() {
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = moduleDAO.getModules();
		return list;
	}

	/**
	 * 根据模块id获取相应题目
	 * 
	 * @param moduleId
	 * @return
	 * @author: cyj
	 * @date: 2017年3月30日 下午7:29:17
	 */
	@RequestMapping(value = "/getModuleDetails")
	@ResponseBody
	public ArrayList<DBRecord> getModuleDetails(@RequestParam(value = "moduleId") int moduleId, HttpSession session) {
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		//System.out.println("#################11111");
		//System.out.println(moduleId+"#");
		//System.out.println("#"+session.getAttribute("teacherid").toString());
		System.err.println(moduleId+"#"+session.getAttribute("userid").toString());
		list = moduleDAO.getModuleDetails(moduleId, session.getAttribute("userid").toString());
		//list = moduleDAO.getModuleDetails(moduleId,"566");
		//String userIdstr=String.valueOf(userId);
		//list = moduleDAO.getModuleDetails(moduleId,userIdstr);
		//System.out.println("#################");
		return list;
	}

	@RequestMapping(value = "/getModuleDetailsByteacher")
	@ResponseBody
	public ArrayList<DBRecord> getModuleDetailsByteacher(@RequestParam(value = "moduleId") int moduleId, HttpSession session) {
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		//System.out.println("#################11111");
		//System.out.println(moduleId+"#");
		//System.out.println("#"+session.getAttribute("teacherid").toString());
		System.err.println(moduleId+"#"+session.getAttribute("teacherid").toString());
		list = moduleDAO.getModuleDetailsByteacher(moduleId, session.getAttribute("teacherid").toString());
		//list = moduleDAO.getModuleDetails(moduleId,"566");
		//String userIdstr=String.valueOf(userId);
		//list = moduleDAO.getModuleDetails(moduleId,userIdstr);
		//System.out.println("#################");
		return list;
	}
	/**
	 * 根据模块id获取当前paperId (已确认存在paper)
	 * 
	 * @author gyh_f
	 */
	@RequestMapping(value = "/getPaperId")
	@ResponseBody
	public Object getPaperId(@RequestParam(value = "moduleId") int moduleId, HttpSession session) {
		String s = new String();
		s = moduleDAO.getPaperId(moduleId, session.getAttribute("userid").toString());
		return ParseUtil.toObject(s);
	}

	/**
	 * 根据模块id获取场景信息
	 * 
	 * @param moduleId
	 * @return
	 * @author: zzh
	 * @date: 2017年10月6日 下午7:29:17
	 */
	@RequestMapping(value = "/getSceneInfo")
	@ResponseBody
	public ArrayList<DBRecord> getSceneInfo(@RequestParam(value = "moduleId") int moduleId, HttpSession session) {
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = moduleDAO.getSceneDetails(moduleId, session.getAttribute("userid").toString());
		return list;
	}

	/***
	 * yanglin
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/dealFeedback2")
	@ResponseBody
	public ArrayList<DBRecord> getFeedback(HttpSession session) {
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println("----------------sssss-----" + 0 + "---------------------");
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		System.out.println("----------------sssss-----" + 1 + "---------------------");
		String sql = "select * from DB_FEEDBACK";
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		list = ParseUtil.toDBRecord(resultSet);
		ArrayList<DBRecord> list2 = new ArrayList<DBRecord>();
		for (DBRecord dbRecord : list) {
			if (dbRecord.getInt("USERID") == userId) {
				list2.add(dbRecord);
			}
		}
		Collections.reverse(list2);
		return list2;
	}

	@RequestMapping(value = "/dealFeedbacklt", method = RequestMethod.POST)
	@ResponseBody
	public ArrayList<DBRecord> tDealFeedbacklt(HttpSession session, @RequestParam(value = "id") int feedbackid) {
		System.out.println("----------------sssss-----" + feedbackid + "----^^^^^^^--------------");
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		String sql = "select * from DB_FEEDBACKLT where FEEDBACKTEXTID='" + feedbackid + "'";
		System.out.println("----------------ididididi-----" + 1 + "---------------------");
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("----------------ididididi-----" + 2 + "---------------------");
		list = ParseUtil.toDBRecord(resultSet);
		System.out.println(list.toString());
		return list;

	}

	/***
	 * yanglin
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/dealFeedback3")
	@ResponseBody
	public ArrayList<DBRecord> tGetFeedback(HttpSession session) {
		System.out.println("----------------sssss----eeeee-" + 1222222 + "---------------------");
		int userId = Integer.parseInt(session.getAttribute("ano").toString());
		System.out.println("----------------sssss-----" + userId + "---------------------");
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		System.out.println("----------------sssss-----" + 1 + "---------------------");
		String sql = "select * from DB_FEEDBACK";
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		list = ParseUtil.toDBRecord(resultSet);
		String sql2 = "select * from DB_COURSE_USER where ANO=" + userId;

		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql2);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<DBRecord> myStulist = new ArrayList<DBRecord>();

		myStulist = ParseUtil.toDBRecord(resultSet);

		ArrayList<DBRecord> list2 = new ArrayList<DBRecord>();

		for (DBRecord dbRecord : list) {
			for (DBRecord dbRecord2 : myStulist)
				if (dbRecord.getInt("USERID") == dbRecord2.getInt("USERID")) {
					list2.add(dbRecord);
				}
		}
		Collections.reverse(list2);
		return list2;
	}

	@RequestMapping(value = "/dealFeedback", method = RequestMethod.POST)
	@ResponseBody
	public DBRecord dealFeedback(HttpSession session, @RequestParam(value = "message") String message,
			@RequestParam(value = "text") String text, @RequestParam(value = "type") String type) {
		DBRecord record = new DBRecord();
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		System.out.println("---------------------" + 0 + "9999-------------------------");
		String feedbackText = message;
		if (feedbackText.trim().isEmpty())
			return null;
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println("---------------------" + userId + "9999-------------------------");
		String sql = "select name from DB_COURSE_USER where userid='" + userId + "'";
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		ArrayList<DBRecord> myStulist = new ArrayList<DBRecord>();

		myStulist = ParseUtil.toDBRecord(resultSet);
		String username = myStulist.get(0).getString("NAME");
		System.out.println("---------------------" + 0 + "9999-----" + myStulist.get(0) + "=====" + username
				+ "---------------------");
		Connection dbConn = null;
		try {
			dbConn = dbDataSource.getConnection();

		} catch (SQLException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		}

		try {
			dbConn.setAutoCommit(false);
			int r = insertUserFeedback(dbConn, userId, feedbackText, type, username, text);
			System.out.println(r);
			dbConn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:" + e1.getMessage());
			}
		} finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				System.out.println("exception:" + e.getMessage());
			}
		}

		System.out.println(message);
		String sql3 = "select top 1 * from DB_FEEDBACK order by id desc";
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql3);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<DBRecord> myStulist3 = new ArrayList<DBRecord>();
		myStulist3 = ParseUtil.toDBRecord(resultSet);
		record = myStulist3.get(0);
		return record;

	}

	// @RequestMapping(value = "/dealFeedback4", method = RequestMethod.POST)
	// @ResponseBody
	// public DBRecord tDealFeedback(HttpSession session, @RequestParam(value =
	// "message") String message,
	// @RequestParam(value = "id") int feedbackid) {
	// String feedbackAns = message;
	// Connection connection = null;
	// Statement statement = null;
	// ResultSet resultSet = null;
	// System.out.println("----------------sssss-----" + feedbackid +
	// "----^^^^^^^--------------");
	// // int userId =
	// // Integer.parseInt(session.getAttribute("ano").toString());
	// System.out.println("---------------------" + 0 +
	// "---------------------");
	// Connection dbConn = null;
	// try {
	// dbConn = dbDataSource.getConnection();
	//
	// } catch (SQLException e) {
	// // e.printStackTrace();
	// System.out.println(e.getMessage());
	// }
	//
	// try {
	// dbConn.setAutoCommit(false);
	// int r = UpdateUserFeedback(dbConn, feedbackid, feedbackAns);
	// String sql2 = "select * from DB_FEEDBACK where ID=" + feedbackid;
	// connection = dbDataSource.getConnection();
	// statement = connection.createStatement();
	// resultSet = statement.executeQuery(sql2);
	// System.out.println(r);
	// dbConn.commit();
	// } catch (SQLException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// try {
	// dbConn.rollback();
	// } catch (SQLException e1) {
	// System.out.println("exception:" + e1.getMessage());
	// }
	// } finally {
	// try {
	// dbConn.close();
	// } catch (SQLException e) {
	// System.out.println("exception:" + e.getMessage());
	// }
	// }
	// ArrayList<DBRecord> myStulist = new ArrayList<DBRecord>();
	//
	// myStulist = ParseUtil.toDBRecord(resultSet);
	//
	// System.out.println(message);
	//
	// return myStulist.get(0);
	//
	// }

	@RequestMapping(value = "/dealFeedbacklttea", method = RequestMethod.POST)
	@ResponseBody
	public DBRecord DealFeedbacklttea(HttpSession session, @RequestParam(value = "message") String message,
			@RequestParam(value = "id") int feedbackid) {
		DBRecord record = new DBRecord();
		String feedbackAns = message;
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		System.out.println(
				"----------------ssxxxxxxxxxxxxxxxxxxxxxxxxxxxx-----" + feedbackid + "----^^^^^^^--------------");
		int userId = Integer.parseInt(session.getAttribute("teacherid").toString());
		System.out.println("---------------------" + 0 + "---------------------");
		Connection dbConn = null;
		try {
			dbConn = dbDataSource.getConnection();

		} catch (SQLException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		}
		String sql = "select tname from DB_COURSE_TEACHER where teacherid='" + userId + "'";
		System.out.println("---------------------" + sql + "---------------------");
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		ArrayList<DBRecord> myStulist = new ArrayList<DBRecord>();

		myStulist = ParseUtil.toDBRecord(resultSet);
		String username = myStulist.get(0).getString("TNAME");
		System.out.println("---------------------" + username + "---------------------");
		try {
			dbConn.setAutoCommit(false);
			int r = insertUserFeedbacklt(dbConn, userId, username, feedbackid, feedbackAns);
			System.out.println(r);
			dbConn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:" + e1.getMessage());
			}
		} finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				System.out.println("exception:" + e.getMessage());
			}
		}

		System.out.println(message);
		String sql3 = "select top 1 * from DB_FEEDBACKLT where FEEDBACKTEXTID='" + feedbackid + "' order by id desc";
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql3);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<DBRecord> myStulist3 = new ArrayList<DBRecord>();
		myStulist3 = ParseUtil.toDBRecord(resultSet);
		record = myStulist3.get(0);
		return record;
	}

	@RequestMapping(value = "/dealFeedbackltstu", method = RequestMethod.POST)
	@ResponseBody
	public DBRecord DealFeedbackltstu(HttpSession session, @RequestParam(value = "message") String message,
			@RequestParam(value = "id") int feedbackid) {
		DBRecord record = new DBRecord();
		String feedbackAns = message;
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		System.out.println(
				"----------------ssxxxxxxxxxxxxxxxxxxxxxxxxxxxx-----" + feedbackid + "----^^^^^^^--------------");
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println("---------------------" + 0 + "---------------------");
		Connection dbConn = null;
		try {
			dbConn = dbDataSource.getConnection();

		} catch (SQLException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		}
		String sql = "select name from DB_COURSE_USER where userid='" + userId + "'";
		System.out.println("---------------------" + sql + "---------------------");
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		ArrayList<DBRecord> myStulist = new ArrayList<DBRecord>();

		myStulist = ParseUtil.toDBRecord(resultSet);
		String username = myStulist.get(0).getString("NAME");
		System.out.println("---------------------" + username + "---------------------");
		try {
			dbConn.setAutoCommit(false);
			int r = insertUserFeedbacklt(dbConn, userId, username, feedbackid, feedbackAns);
			System.out.println(r);
			dbConn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:" + e1.getMessage());
			}
		} finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				System.out.println("exception:" + e.getMessage());
			}
		}

		System.out.println(message);
		String sql3 = "select top 1 * from DB_FEEDBACKLT where FEEDBACKTEXTID='" + feedbackid + "' order by id desc";
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql3);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<DBRecord> myStulist3 = new ArrayList<DBRecord>();
		myStulist3 = ParseUtil.toDBRecord(resultSet);
		record = myStulist3.get(0);
		return record;
	}

	private int UpdateUserFeedback(Connection dbConn, int feedbackid, String feedbackAns) {
		// TODO Auto-generated method stub
		Connection connection = null;
		Statement statement = null;
		int result = 0;
		String sql = "UPDATE DB_FEEDBACK set FEEDBACKANS='" + feedbackAns + "' where Id=" + feedbackid;
		System.out.println(sql);
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			result = statement.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	//判断老师输入的答案语法是否正确
			@RequestMapping(value = "/checkSyntax")
			@ResponseBody
			public boolean checkSyntax(@RequestParam(value = "answerSql") String answerSql) {
				Connection samConn = null;
				Statement stmt = null;
				boolean rs ;
				Savepoint sp = null;
				boolean syn=true;
				try {
					samConn = samplesDataSource.getConnection();
					samConn.setAutoCommit(false);// 通知数据库开启事务(start transaction)
					stmt = samConn.createStatement();
					sp = samConn.setSavepoint();
					rs = stmt.execute(answerSql);
					samConn.rollback(sp);
				} catch (SQLException e) {
					syn=false;
					System.out.println(e.getMessage());
				}
				return syn;
			}
	/**
	 * 处理用户的答案
	 * 
	 * @param message
	 * @return
	 * @author: cyj
	 * @throws Exception
	 * @date: 2017年3月31日 下午3:12:31
	 */
	@RequestMapping(value = "/judgetUserModuleSolutions", method = RequestMethod.POST)
	@ResponseBody
	public Object judgetUserModuleSolutions(HttpSession session, @RequestParam(value = "message") String message,
			@RequestParam(value = "paperId") String paperId) {
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		int totalScore = 0;
		String userSolution = "";
		String standardSolution = "";
		String extraString = "";
		int moduleId = 0;
		int expId = 0;
		Map<Integer, Integer> scoreMap = new HashMap<Integer, Integer>();
		Map<Integer, String> userSolutionMap = new HashMap<Integer, String>();

		JSONArray jaArray = JSON.parseArray(message);
		//		System.out.println(message.toString());

		// 获取数据库连接
		Connection samConn = null;
		Connection dbConn=null;
		try {
			samConn = samplesDataSource.getConnection();
			dbConn=dbDataSource.getConnection();
		} catch (SQLException e) {
			//			e.printStackTrace();
			System.out.println(e.getMessage());
		}

		for (int count = 0; count < jaArray.size(); count++) {
			JSONObject jobj = jaArray.getJSONObject(count);
			moduleId = jobj.getIntValue("MODULEID");
			expId = jobj.getIntValue("EXPID");
			userSolution = jobj.containsKey("userSolution") ? jobj.getString("userSolution") : "";
			standardSolution = jobj.getString("SOLUTION");
			extraString = jobj.getString("EXTRA");		

			//解码
			EncryptionDecryption des=null;
			try {
				des = new EncryptionDecryption("leemenz");
				userSolution = new String(des.decode(userSolution));
				standardSolution=new String(des.decode(standardSolution));
				extraString = new String(des.decode(extraString));
			} catch (Exception e) {
				e.printStackTrace();
			}		
			System.out.println("after===== "+userSolution);

			int score = solveUserSolutions(samConn, session, count, moduleId, expId, standardSolution,
					userSolution, extraString);
			userSolutionMap.put(expId, userSolution);
			scoreMap.put(expId, score);//将题号跟对应的分数保存到scoreMap中
			totalScore += score;
			System.out.println("++++++++++++" + count);
		}
		System.out.println("---" + totalScore + "----");
		try {
			samConn.close();
		} catch (SQLException e) {
			//			e.printStackTrace();
			System.out.println(e.getMessage());
		}finally{
		}

		//只要有一个保存了就所有的都保存了（前提是所以的保存都在一个transaction）
		boolean isHaveSaved=false;
		try {
			dbConn.setAutoCommit(false);
			for (int count = 0; count < jaArray.size(); count++) {
				JSONObject jobj = jaArray.getJSONObject(count);
				moduleId = jobj.getIntValue("MODULEID");
				expId = jobj.getIntValue("EXPID");
				if (count==0) {//只要改模块有一题保存了就说明保存过
					isHaveSaved = isHaveSaved(dbConn,userId, moduleId, expId,paperId);
				}
				userSolution = userSolutionMap.get(expId);
				int score = scoreMap.get(expId);//得到该题的分数
				int errData = score == 0 ? 0 : score == 10 ? 1 : 2; // 0 wrong;1 right;2 half right
				int eStatus = 1;//提交状态
				modifyUserExpStatus(dbConn,userId, moduleId, expId, userSolution, errData, eStatus, score, isHaveSaved,paperId);
			}
			modifyUserModuleScore(dbConn, userId, moduleId, totalScore,paperId);
			dbConn.commit();
		} catch (SQLException e) {
			System.out.println("exception:"+e.getMessage());
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:"+e1.getMessage());
			}
		}finally{
			try {
				dbConn.close();
			} catch (SQLException e) {
				System.out.println("exception:"+e.getMessage());
			}
		}
		return ParseUtil.toObject(totalScore + "");
	}
	/*
	@RequestMapping(value = "/judgetUserModuleSolutions", method = RequestMethod.GET)
	@ResponseBody
	public Object judgetUserModuleSolutions(HttpSession session, @RequestParam(value = "message") String message,
			@RequestParam(value = "paperId") String paperId) throws Exception {
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		int totalScore = 0;
		String userSolution = "";
		String standardSolution = "";
		String extraString = "";
		int moduleId = 0;
		int expId = 0;
		int befModuleId = 0;
		int befExpId = 0;
		Map<Integer, Integer> scoreMap = new HashMap<Integer, Integer>();
		Map<Integer, String> userSolutionMap = new HashMap<Integer, String>();

		JSONArray jaArray = JSON.parseArray(message);
		// System.out.println(message.toString());

		// 获取数据库连接
		Connection samConn = null;
		Connection dbConn = null;
		try {
			samConn = samplesDataSource.getConnection();
			dbConn = dbDataSource.getConnection();
		} catch (SQLException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		}

		for (int count = 0; count < jaArray.size(); count++) {
			JSONObject jobj = jaArray.getJSONObject(count);
			System.out.println(jobj);
			moduleId = jobj.getIntValue("MODULEID");
			expId = jobj.getIntValue("EXPID");
			userSolution = jobj.containsKey("userSolution") ? jobj.getString("userSolution") : "";
			standardSolution = jobj.getString("SOLUTION");
			System.out.println("before----staS" + standardSolution);
			extraString = jobj.getString("EXTRA");
			befModuleId = jobj.getIntValue("BEFOREMODULEID");
			befExpId = jobj.getIntValue("BEFOREEXPID");

			// 解码

			// EncryptionDecryption des = null;
			try {
				// des =new EncryptionDecryption("tourhb");

				userSolution = new String(EncryptionDecryption.decode(userSolution), "UTF-8");
				standardSolution = new String(EncryptionDecryption.decode(standardSolution), "UTF-8");
				extraString = new String(EncryptionDecryption.decode(extraString));
				System.out.println("ttttttt" + standardSolution);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("after解码===== " + userSolution);

			// standardSolution的解码有问题
			// dXBkYXRlIFNDIHNldCBjbm89KHNlbGVjdCBjbm8gZnJvbSBjb3Vyc2Ugd2hlcmUgY25hbWU9J+aTjeS9nOezu+e7n+Wunui3tScpIHdoZXJlIHNu
			// （接着上一段）bz0nMjAxNzAwMTAwMScgYW5kIGNubyBpbiAoc2VsZWN0IGNubyBmcm9tIGNvdXJzZSB3aGVyZSBjbmFtZT0n55S15a2Q5ZWG5Yqh5qaC6K66JykK
			System.out.println("after解码===== " + standardSolution);

			int score = solveUserSolutions(samConn, dbConn, session, count, moduleId, expId, standardSolution,
					userSolution, extraString, befModuleId, befExpId);
			userSolutionMap.put(expId, userSolution);
			scoreMap.put(expId, score);// 将题号跟对应的分数保存到scoreMap中
			totalScore += score;
			System.out.println("++++++++++++" + count);
		}

		System.out.println("---" + totalScore + "----");
		try {
			samConn.close();
		} catch (SQLException e) {
			// e.printStackTrace();
			System.out.println(e.getMessage());
		} finally {
		}

		// 只要有一个保存了就所有的都保存了（前提是所有的保存都在一个transaction）
		boolean isHaveSaved = false;
		try {
			dbConn.setAutoCommit(false);
			for (int count = 0; count < jaArray.size(); count++) {
				JSONObject jobj = jaArray.getJSONObject(count);
				moduleId = jobj.getIntValue("MODULEID");
				expId = jobj.getIntValue("EXPID");
				if (count == 0) {// 只要有一题保存了就说明保存过
					isHaveSaved = isHaveSaved(dbConn, userId, moduleId, expId, paperId);
				}
				userSolution = userSolutionMap.get(expId);
				int score = scoreMap.get(expId);// 得到该题的分数
				int errData = score == 0 ? 0 : score == 10 ? 1 : 2; // 0 wrong;1
																	// right;2
																	// half
																	// right
				int eStatus = 1;// 提交状态
				System.out.println("paperId@modify-----" + paperId);
				modifyUserExpStatus(dbConn, userId, moduleId, expId, userSolution, errData, eStatus, score, isHaveSaved,
						paperId);
			}
			modifyUserModuleScore(dbConn, userId, moduleId, totalScore, paperId);
			dbConn.commit();
		} catch (SQLException e) {
			System.out.println("exception:" + e.getMessage());
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:" + e1.getMessage());
			}
		} finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				System.out.println("exception:" + e.getMessage());
			}
		}
		return ParseUtil.toObject(totalScore + "");
	}
	*/

	/**
	 * 保存用户的答案
	 * 
	 * @param session
	 * @param message
	 * @return
	 * @author: cyj
	 * @date: 2017年4月3日 下午6:23:42
	 */
	@RequestMapping(value = "/saveUserModuleSolutions", method = RequestMethod.POST)
	@ResponseBody
	public Object saveUserModuleSolutions(HttpSession session, @RequestParam(value = "message") String message,
			@RequestParam(value = "paperId") String paperId) {
		String userSolution = "";
		int moduleId = 0;
		int expId = 0;
		String info = "";
		boolean isHaveSubmitted = false;
		boolean isHaveSaved = false;
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		JSONArray jaArray = JSON.parseArray(message);

		Connection dbConn = null;
		try {
			dbConn = dbDataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		// 遍历答案
		try {
			dbConn.setAutoCommit(false);
			for (int count = 0; count < jaArray.size(); count++) {
				JSONObject jobj = jaArray.getJSONObject(count);
				userSolution = jobj.containsKey("userSolution") ? jobj.getString("userSolution") : "";
				moduleId = jobj.getIntValue("MODULEID");
				expId = jobj.getIntValue("EXPID");

				EncryptionDecryption des = null;
				try {
					// des = new EncryptionDecryption("leemenz");
					userSolution = new String(EncryptionDecryption.decode(userSolution));
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (count == 0) {
					// gyh note:isHaveSaved?
					isHaveSaved = isHaveSaved(dbConn, userId, moduleId, expId, paperId);
					// gyh note:isHaveSubmitted?
					isHaveSubmitted = isHaveSubmitted(dbConn, userId, moduleId, expId, paperId);
				}
				if (isHaveSubmitted) {
					return ParseUtil.toObject("save failure");
				}
				// gyh note:change here!
				saveUserSolutions(session, dbConn, moduleId, expId, userSolution, isHaveSaved, paperId);
			}
			dbConn.commit();// 全部循环结束再统一提交保存
		} catch (SQLException e) {
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:" + e1.getMessage());
			}
			System.out.println("exception:" + e.getMessage());
		} finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// e.printStackTrace();
				System.out.println("exception:" + e.getMessage());
			}
		}
		return ParseUtil.toObject("save success");
	}

	/**
	 * 保存用户临时提交的答案
	 * 
	 * @param session
	 * @param moduleId
	 * @param expId
	 * @param userSolution
	 * @return
	 * @author: cyj
	 * @throws SQLException
	 * @date: 2017年4月3日 下午7:22:10
	 */
	private void saveUserSolutions(HttpSession session, Connection conn, int moduleId, int expId, String userSolution,
			boolean isHaveSaved, String paperId) throws SQLException {
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println(userSolution);
		int errData = 3; // 0 wrong;1 right;2 half right,3没提交
		int eStatus = 2; // 1 提交 2 临时保存
		// gyh note
		modifyUserExpStatus(conn, userId, moduleId, expId, userSolution, errData, eStatus, 0, isHaveSaved, paperId);
	}

	/**
	 * 根据moduleId进行不同的判断逻辑：select 、update等
	 * 
	 * @param moduleId
	 * @param standardSolution
	 * @param userSolution
	 * @author: cyj
	 * @date: 2017年3月31日 下午3:27:26
	 */
	private int solveUserSolutions(Connection conn, HttpSession session, int count, int moduleId, int expId,
			String standardSolution, String userSolution, String extraString) {
		userSolution=userSolution.replace('\n',' ');
		standardSolution=standardSolution.replace('\n',' ');
		userSolution=userSolution.replace('\r',' ');
		standardSolution=standardSolution.replace('\r',' ');
		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println("session--" + userId);
		System.out.println("---execute-----" + userSolution);
		if (session.getAttribute("name") == null) {
			return 0;
		}

		int score = 0;
		if (userSolution.length() < 4) {
			score = 0;
		} else {
			//去掉字符串最后的分号
			userSolution = StringUtils.substringBeforeLast(userSolution, ";").trim();
			System.out.println("###############"+moduleId+"#################1");
			if (moduleId == 51 || moduleId == 52) {// 单表。多表查询
				score = sqlJudgeService.selectJudge(conn, standardSolution, userSolution, extraString);
			} else if (moduleId == 55) {
				score = sqlJudgeService.tableJudge(conn, userSolution, extraString);
			} else if (moduleId == 56) {
				score = sqlJudgeService.indexJudge(conn, userSolution, extraString);
			} else if (moduleId == 57) {
				score = sqlJudgeService.viewJudge(conn, userSolution, extraString);
			}else if (moduleId == 58) {
				score = sqlJudgeService.authJudge(conn,userSolution,extraString);
			}else if (moduleId == 61) {
				score = sqlJudgeService.entityJudge(conn, userSolution, extraString);
			} else if (moduleId == 62) {
				score = sqlJudgeService.updateJudge1(conn, userSolution, standardSolution,extraString);//change zk
				//score = sqlJudgeService.updateJudge(conn, userSolution,extraString);//change zk
			} else if (moduleId == 63) {
				score = sqlJudgeService.referJudge(conn, userSolution, extraString);
			} else if (moduleId == 66) {
				score = sqlJudgeService.triggerJudge(conn, userSolution, extraString);
			} else if (moduleId == 67) {
				score = sqlJudgeService.saveProcessJudge(conn, userSolution, extraString);
			}
		}
		System.out.println("judged completed");

		return score;
	}
	/*修改
	private int solveUserSolutions(Connection conn, Connection dbConn, HttpSession session, int count, int moduleId,
			int expId, String standardSolution, String userSolution, String extraString, int befModuleId,
			int befExpId) {

		int userId = Integer.parseInt(session.getAttribute("userid").toString());
		System.out.println("session--" + userId);
		System.out.println("---execute-----" + userSolution);

		if (session.getAttribute("name") == null) {
			return 0;
		}

		int score = 0;
		if (userSolution.length() < 1) {
			score = 0;
		} else {
			// 去掉字符串最后的分号
			userSolution = StringUtils.substringBeforeLast(userSolution, ";").trim();
			if (moduleId == 51 || moduleId == 52 || moduleId == 62) {
				score = sqlJudgeService.ExplainJudge(conn, dbConn, userSolution, standardSolution, befModuleId,
						befExpId);
			} else {
				score = sqlJudgeService.unExplainJudge(conn, dbConn, userSolution, standardSolution, befModuleId,
						befExpId);
			}

			// if (moduleId == 51 || moduleId == 52) {// 单表。多表查询
			// score = sqlJudgeService.selectJudge(conn, standardSolution,
			// userSolution, extraString);
			// } else if (moduleId == 55) {
			// score = sqlJudgeService.tableJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 56) {
			// score = sqlJudgeService.indexJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 57) {
			// score = sqlJudgeService.viewJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 58) {
			// score = sqlJudgeService.authJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 61) {
			// score = sqlJudgeService.entityJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 62) {
			// score = sqlJudgeService.updateJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 63) {
			// score = sqlJudgeService.referJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 66) {
			// score = sqlJudgeService.triggerJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 67) {
			// score = sqlJudgeService.saveProcessJudge(conn, userSolution,
			// extraString);
			// } else if (moduleId == 71) {
			// score = sqlJudgeService.RollbackJudge(conn, userSolution,
			// extraString);
			// }
		}
		System.out.println("judged completed");

		return score;
	}
	*/
	/**
	 * 判断用户是否已经提交（保存）过该模块的答案
	 * 
	 * @param userId
	 * @param moduleId
	 * @return
	 * @author: cyj
	 * @date: 2017年3月26日 下午1:23:50
	 */
	private boolean isHaveSaved(Connection conn, int userId, int moduleId, int expid, String paperId) {
		int count = 0;
		String sql = "select count(*) from PUBLIC.USER_EXP_STATUS where USERID = " + userId + " and MODULEID = "
				+ moduleId + " and EXPID = " + expid + " and ESTATUS = 2 and PAPERID = '" + paperId + "'";

		// String sql = "select count(*) from PUBLIC.USER_EXP_STATUS where
		// PAPERID = "+paperId+" and USERID = "+userId;
		try {
			count = Integer.parseInt(dbCourseDAO.queryOne(conn, sql));
		} catch (NumberFormatException | SQLException e) {
			e.printStackTrace();
		}

		return count > 0 ? true : false;
	}

	/**
	 * 判断是否已经提交过
	 * 
	 * @param userId
	 * @param moduleId
	 * @param expid
	 * @return
	 * @author: cyj
	 * @date: 2017年4月6日 下午2:29:51
	 */
	private boolean isHaveSubmitted(Connection conn, int userId, int moduleId, int expid, String paperId) {
		int count = 0;
		String sql = "select * from PUBLIC.USER_EXP_STATUS where USERID = " + userId + " and MODULEID = " + moduleId
				+ " and EXPID = " + expid + " and ESTATUS = 1 and PAPERID = " + paperId;
		try {
			ArrayList<DBRecord> records = (dbCourseDAO.query(conn, sql));
			if (records.size() > 0) {
				for (int i = 0; i < records.size(); i++) {
					DBRecord record = records.get(i);
					int estatus = Integer.parseInt(record.getString("ESTATUS"));
					if (estatus == 1) {// 已经提交过了
						return true;
					} else {
						return false;
					}
				}
			} else {
				return false;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 插入用户对于某道题目的完成状态和答案
	 * 
	 * @param userId
	 *            用户id
	 * @param moduleId
	 *            该类型操作
	 * @param expId
	 *            该类型的第几道
	 * @param solution
	 *            用户的答案
	 * @param errData
	 *            0：错误 1：正确 2:不完全正确 3：未评分（用于临时保存）
	 * @param eStatus
	 *            1：已做(已提交) 2：临时保存
	 * @param 该小题的分数
	 * @return
	 * @throws SQLException
	 */
	private String insertUserExpStatus(Connection conn, int userId, int moduleId, int expId, String userSolution,
			int errData, int eStatus, int score, String paperId) throws SQLException {
		System.out.println("insertUserExpStatus");
		DBRecord record = new DBRecord();
		record.setField("USERID", "" + userId);
		record.setField("MODULEID", "" + moduleId);
		record.setField("EXPID", "" + expId);
		record.setField("SOLUTION", userSolution.replaceAll("'", "''"));
		record.setField("ERRDATA", "" + errData);
		record.setField("ESTATUS", "" + eStatus);
		record.setField("SCORE", "" + score);
		record.setField("PAPERID", "" + paperId);

		String result = dbCourseDAO.insertUserExpStatus(conn, "USER_EXP_STATUS", record);
		return result;
	}

	/**
	 * 如果status为2或user_exp_status中已经存在该module的记录，则证明已经保存过，更新用户对于某道题目的完成状态和答案
	 * 
	 * @param userId
	 *            用户id
	 * @param moduleId
	 *            该类型操作
	 * @param expId
	 *            该类型的第几道
	 * @param solution
	 *            用户的答案
	 * @param errData
	 *            0：错误 1：正确 2:不完全正确 3：未判分
	 * @param eStatus
	 *            1：已做 2:临时保存
	 * @return
	 * @throws SQLException
	 */
	private DBRecord updateUserExpStatus(Connection conn, int userId, int moduleId, int expId, String solution,
			int errData, int eStatus, int score, String paperId) throws SQLException {
		System.out.println("updateUserExpStatus");
		DBRecord dbr = new DBRecord();
		dbr.setField("USERID", "" + userId);
		dbr.setField("MODULEID", "" + moduleId);
		dbr.setField("EXPID", "" + expId);
		dbr.setField("SOLUTION", solution.replaceAll("'", "''"));
		dbr.setField("ERRDATA", "" + errData);
		dbr.setField("ESTATUS", "" + eStatus);
		dbr.setField("SCORE", "" + score);
		dbr.setField("PAPERID", "" + paperId);
		DBRecord dbrCondition = new DBRecord();
		dbrCondition.setField("USERID", "" + userId);
		dbrCondition.setField("MODULEID", "" + moduleId);
		dbrCondition.setField("EXPID", "" + expId);
		dbrCondition.setField("PAPERID", "" + paperId);
		dbCourseDAO.updateUserExpStatus(conn, "USER_EXP_STATUS", dbr, dbrCondition);
		return dbr;
	}

	/**
	 * 插入用户对于某道题目的完成状态和答案
	 * 
	 * @param userId
	 *            用户id
	 * @param moduleId
	 *            该类型操作
	 * @param expId
	 *            该类型的第几道
	 * @param solution
	 *            用户的答案
	 * @param errData
	 *            0：错误 1：正确 2:不完全正确 3：未评分（用于临时保存）
	 * @param eStatus
	 *            1：已做(已提交) 2：临时保存
	 * @param 该小题的分数
	 * @return
	 * @throws SQLException
	 */
	private String insertUserModuleScore(Connection conn, int userId, int moduleId, int totalScore, String paperId)
			throws SQLException {
		DBRecord record = new DBRecord();
		record.setField("USERID", "" + userId);
		record.setField("MODULEID", "" + moduleId);
		record.setField("SCORE", "" + totalScore);
		record.setField("PAPERID", "" + paperId);
		String result = dbCourseDAO.insertUserModuleScore(conn, "USER_MODULE_SCORE", record);
		return result;
	}

	/**
	 * yanglin
	 * 
	 * @param conn
	 * @param userId
	 * @param feedbacktext
	 * @return
	 * @throws SQLException
	 */
	private int insertUserFeedback(Connection conn, int userId, String feedbacktext, String type, String username,
			String text) throws SQLException {
		DBRecord record = new DBRecord();
		record.setField("USERNAME", "" + username);
		record.setField("USERID", "" + userId);
		record.setField("FEEDBACKTEXT", feedbacktext);
		record.setField("FEEDBACKANS", text);
		record.setField("FEEDBACKTYPE", type);
		int result = dbCourseDAO.insertUserFeedback(conn, "DB_FEEDBACK", record);
		return result;

	}

	private int insertUserFeedbacklt(Connection conn, int userid, String username, int feedbackid, String feedbackAns)
			throws SQLException {
		// TODO Auto-generated method stub
		DBRecord record = new DBRecord();
		record.setField("USERNAME", "" + username);
		record.setField("USERID", "" + userid);
		record.setField("FEEDBACKTEXTID", "" + feedbackid);
		record.setField("FEEDBACKANS", "" + feedbackAns);
		int result = dbCourseDAO.insertUserFeedback(conn, "DB_FEEDBACKLT", record);
		return result;
	}

	/**
	 * 修改user_exp_status表中的信息 插入或更新的方式
	 * 
	 * @param userId
	 *            用户id
	 * @param moduleId
	 *            该类型操作
	 * @param expId
	 *            该类型的第几道
	 * @param solution
	 *            用户的答案
	 * @param errData
	 *            0：错误 1：正确 2:不完全正确 3：未评分（用于临时保存）
	 * @param eStatus
	 *            1：已做 2：临时保存
	 * @param score
	 *            该小题的分数
	 * @param isHaveSaved
	 * @return
	 * @author: cyj
	 * @throws SQLException
	 * @date: 2017年3月26日 下午2:08:12
	 */
	private void modifyUserExpStatus(Connection conn, int userId, int moduleId, int expId, String userSolution,
			int errData, int eStatus, int score, boolean isHaveSaved, String paperId) throws SQLException {
		System.out.println("modifyUserExpStatus");
		if (isHaveSaved) {
			updateUserExpStatus(conn, userId, moduleId, expId, userSolution, errData, eStatus, score, paperId);
		} else {
			insertUserExpStatus(conn, userId, moduleId, expId, userSolution, errData, eStatus, score, paperId);
		}
	}

	private void modifyUserModuleScore(Connection conn, int userId, int moduleId, int totalScore, String paperId)
			throws SQLException {
		System.out.println("modifyUserModuleScore");
		insertUserModuleScore(conn, userId, moduleId, totalScore, paperId);
	}

}
